<template>
  <div class="text-r">
    <el-date-picker
      v-model="dataRange"
      type="monthrange"
      clear-icon="icon-none"
      range-separator="-"
      :start-placeholdeturr="$t('chart.start')"
      :end-placeholder="$t('chart.end')"
      :clearable="false"
      class="chart-date-range-picker"
      @change="initChart()"
      :picker-options="pickerOptions"
      style="width:147px"
    >
    </el-date-picker>
    <!-- <div>
      <select v-model="">
        <option v-for="item in 2020" :key="item" value="item">{{item}}</option>
      </select>
      <select v-model="">
        <option v-for="item in 31" :key="item" value="item">{{item}}</option>
      </select>
      -
      <select v-model="">
        <option v-for="item in 2020" :key="item" value="item">{{item}}</option>
      </select>
      <select v-model="">
        <option v-for="item in 31" :key="item" value="item">{{item}}</option>
      </select>
    </div> -->
    <div
      ref="chartContainer"
      :style="'width:' + width + ';height:' + height + ';'"
      style="position:relative;margin-bottom:5px;"
    >
      <div ref="chart" :style="'height:' + height + ';margin-top:-20px;'"></div>
    </div>
  </div>
</template>
<script>
import * as Echarts from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import {
  LegendComponent,
  TooltipComponent,
  ToolboxComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { queryNetAssets } from '@/assets/api/index.js'
import { greaterThanEqualsAfter30Days } from '@/assets/utils/commonUtil'
Echarts.use([
  LegendComponent,
  TooltipComponent,
  ToolboxComponent,
  GridComponent,
  LineChart,
  BarChart,
  CanvasRenderer
])
export default {
  data () {
    return {
      chart: {},
      dataRange: [new Date(new Date() - 31535000000), new Date()],
      pickerOptions: { disabledDate: greaterThanEqualsAfter30Days },
      options: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          position: this.setToolTipsPosition,
          formatter: this.formatTooltips
        },
        legend: {
          data: [
            this.$t('chart.type.netAsset'),
            this.$t('chart.type.liability'),
            this.$t('chart.type.borrow'),
            this.$t('chart.type.income')
          ],
          left: 'left'
        },
        toolbox: {
          show: true,
          left: 'right',
          orient: 'vertical',
          emphasis: {
            iconStyle: {
              textPosition: 'left',
              textBackgroundColor: 'rgba(0,100,220,0.6)',
              textPadding: 4,
              textFill: '#ddd'
            }
          },
          padding: [35, 5, 5, 5],
          feature: {
            saveAsImage: {
              show: true,
              name: 'chart',
              title: this.$t('chart.toolBox.title.saveAsImage')
            },
            magicType: {
              type: ['line', 'bar'],
              title: {
                line: this.$t('chart.toolBox.title.switchingToLineGraph'),
                bar: this.$t('chart.toolBox.title.switchingToBarGraph')
              }
            }
          }
        },
        grid: {
          left: '0px',
          right: '30px',
          top: '30px',
          bottom: '0px',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            formatter: (value, index) => {
              return this.$d(new Date(value), 'yearMonth')
            }
          },
          data: []
        },
        yAxis: [
          {
            type: 'value',
            scale: true // y轴从数据的最小值开始
          }
        ],
        series: [
          {
            name: this.$t('chart.type.netAsset'),
            data: [],
            type: 'line',
            areaStyle: {}
          },
          {
            name: this.$t('chart.type.liability'),
            data: [],
            type: 'line',
            areaStyle: {}
          },
          {
            name: this.$t('chart.type.borrow'),
            data: [],
            type: 'line',
            areaStyle: {}
          },
          {
            name: this.$t('chart.type.income'),
            data: [],
            type: 'line',
            areaStyle: {}
          }
        ],
        axisLabel: {}
      }
    }
  },
  props: { width: { type: String }, height: { type: String } },
  mounted () {
    // this.$refs.chart.width = this.$refs.chartContainer.clientWidth
    this.initChart()
  },
  methods: {
    getNetAssets () {
      this.chart.showLoading()
      const startDate = new Date(
        this.dataRange[0].getFullYear(),
        this.dataRange[0].getMonth(),
        1
      )
      const endDate = new Date(
        this.dataRange[1].getFullYear(),
        this.dataRange[1].getMonth() + 1,
        1
      )
      queryNetAssets({
        startDate: startDate.toUTCString(),
        endDate: endDate.toUTCString()
      }).then(res => {
        const sumData = res.data
        const xAxisData = sumData.map(item => item.dateMonth)
        const netAssets = sumData.map(item => item.netAsset)
        const liabilitys = sumData.map(item => item.liability)
        const borrowing = sumData.map(item => item.borrowing)
        const income = sumData.map(item => item.income)
        this.options.xAxis.data = xAxisData
        this.options.series[0].data = netAssets
        this.options.series[1].data = liabilitys
        this.options.series[2].data = borrowing
        this.options.series[3].data = income
        this.chart.setOption(this.options)
        this.chart.hideLoading()
      })
    },
    initChart () {
      this.chart = Echarts.init(this.$refs.chart)
      const VueObj = this
      this.getNetAssets()
      window.onresize = () => {
        VueObj.$refs.chart.style.width =
          VueObj.$refs.chartContainer.clientWidth + 'px'
        VueObj.chart.resize()
      }
    },
    formatTooltips (params, ticket, cb) {
      const frame = document.createElement('div')
      const title = document.createElement('span')
      frame.append(title)
      title.innerText = this.$d(new Date(params[0].axisValueLabel), 'yearMonth')
      const tooltipTable = document.createElement('table')
      frame.appendChild(tooltipTable)
      params.forEach((item, index) => {
        const change = document.createElement('span')
        if (item.dataIndex > 0) {
          const changeNumber =
            parseFloat(item.data) -
            parseFloat(
              this.options.series[item.seriesIndex].data[item.dataIndex - 1]
            )
          const defaultStyle = 'margin-left:5px;font-size:12px;'
          const fontColor =
            changeNumber > 0
              ? 'color:red;'
              : changeNumber < 0
                ? 'color:green;'
                : ''
          change.setAttribute('style', defaultStyle + fontColor)
          change.innerText =
            (changeNumber > 0 ? '+' : '') + changeNumber.toFixed(2)
        }
        const tooltipRow = document.createElement('tr')
        const tooltipColIcon = document.createElement('td')
        const tooltipColLabel = document.createElement('td')
        const tooltipColValue = document.createElement('td')
        const tooltipIcon = document.createElement('div')
        tooltipRow.appendChild(tooltipColIcon)
        tooltipRow.appendChild(tooltipColLabel)
        tooltipRow.appendChild(tooltipColValue)
        tooltipRow.setAttribute('style', 'text-align:left;')
        tooltipColLabel.setAttribute('style', 'font-weight:bold;')
        tooltipIcon.setAttribute(
          'style',
          'display:inline-block;width:10px;height:10px;margin:3px;border-radius:50%;background-color:' +
            item.color
        )
        tooltipColIcon.appendChild(tooltipIcon)
        tooltipColLabel.innerText = item.seriesName
        tooltipColValue.innerText = item.value
        tooltipColValue.appendChild(change)
        tooltipTable.appendChild(tooltipRow)
        if (index === params.length - 1) {
          cb(ticket, frame.outerHTML)
        }
      })
    },
    setToolTipsPosition (point, params, dom, rect, size) {
      const meetRightMarginX =
        size.viewSize[0] - size.contentSize[0] - (size.viewSize[0] - point[0])
      const xValue =
        point[0] + size.contentSize[0] > size.viewSize[0]
          ? meetRightMarginX
          : point[0]
      return [xValue, 30]
    }
  }
}
</script>
